/**
 * 
 */
package com.rodirod.vrmonitor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author T0008086
 *
 */
public class RaceManager implements Constants {
	private static RaceManager instance_ = null;
	
	/**
	 * List of Map containing at least these couples :
	 *      M_TITLE : name of a property
	 *      M_VALUE : value of the property
	 * This Map value will be completed by a SimpleAdapter for a ListActivity
	 */
	private List<Map<String, Object>> dataAdapter_ = null;
	// map which key is the title of the property and the value is the same as above (shared)
	private Map< String , Map<String,Object> > dataMap_ = null;
	
    /**
     * private constructor - Singleton pattern
     */
    private RaceManager() {
		dataAdapter_ = new ArrayList< Map<String,Object> >();
		dataMap_ = new HashMap<String, Map<String,Object>>();
    }
    
    /**
     * return the singleton instance
     */
    public final synchronized static RaceManager getInstance() {
        if (instance_ == null) 
        	instance_ = new RaceManager();
        return instance_;
    }
    
    /**
     * 
     * @param name
     * @param urlPath
     * @return true if ok, false in case of error
     */
    public final synchronized boolean addRace(String name, String key, String urlPath) {
		
		RaceInfo info = new RaceInfo(name,urlPath);
		boolean result = info.readDataFromUrl();
		
		Map<String,Object> data = new HashMap<String,Object>();
		data.put(M_REGATE_INFO, info);
		data.put(M_REGATE_KEY, key);
		data.put(M_REGATE_URL, urlPath);
		data.put(M_REGATE_NAME, name);

    	dataMap_.put(name, data);
    	dataAdapter_.add(data);
    	
    	return result;
    }
    
    public final synchronized RaceInfo getRace(String name) {
    	Map<String,Object> data = dataMap_.get(name);
    	if (null==data) return null;
    	return (RaceInfo)data.get(M_REGATE_INFO);
    }
    
    public final synchronized RaceInfo removeRace(String name) {
    	Map<String,Object> data = dataMap_.remove(name);
    	if (null==data) return null;
    	dataAdapter_.remove(data);
    	return (RaceInfo)data.get(M_REGATE_INFO);
    }
    
	public final synchronized List<Map<String, Object>> getAdapterViewData() {
		return dataAdapter_;
	}

	public void clearAndDestroy() {
		dataMap_.clear();
		dataAdapter_.clear();
	}
    
}
